package com.tzy.user.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tzy.common.entity.User;
import com.tzy.common.utils.EncryptUtil;
import com.tzy.common.utils.RandomUtil;
import com.tzy.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
/**
 * <p>
 * 用户表 服务实现类
 * https://www.cnblogs.com/coding-one/p/12403801.html
 * </p>
 *
 * @author 谭同学
 * @since 2022-02-28
 */
@Slf4j
@Service
public class UserService extends ServiceImpl<UserMapper, User> /*implements IUserService */{
    @Resource
    private UserMapper userMapper;
//    @Resource
//    private RedisService redisService;
    public User loginWithVerificationCode(String username) {
        if (StringUtils.hasText(username)) {
            //条件构造器
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            //Lambda表达式
            queryWrapper.lambda().eq(User::getEmail, username);
            User user = getOne(queryWrapper);
            if (user != null) {
                setToken(user);
                //保存信息到redis里
                //保存信息到redis里
                log.info("保存信息到redis里,userId="+user.getId());
//                redisService.setString(CacheConstant.TOKEN_PREFIX + user.getId(), user.getToken(), 7200);
                user.setPassword(null);
                return user;
            }
        }
        return null;
    }
    public User loginByPassword(String username, String password) {
        //加密后的密码
        String pass = EncryptUtil.getMd5(password);
        if ( StringUtils.hasText(pass) ) {
            //条件构造器
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            //Lambda表达式
            queryWrapper.lambda().eq(User::getEmail, username).eq(User::getPassword, pass);
            User user = getOne(queryWrapper);
            if (user != null) {
                //生成 token
                setToken(user);
                //保存信息到redis里
//                redisService.setString(CacheConstant.TOKEN_PREFIX + user.getId(), user.getToken(), 7200);
                user.setPassword(null);
                return user;
            }
        }
        return null;
    }
    @CacheEvict(value = "user",allEntries = true)
    public void setToken(User user) {
        if (user != null) {
            user.setToken(RandomUtil.genToken());
        }
    }
//    @CacheEvict(value = "user",allEntries = true)
    /**
     * @CachePut 这个注解一般加在更新方法上，当数据库中的数据更新后，缓存中的数据也要跟着更新，
     * 使用该注解，可以将方法的返回值自动更新到已经存在的 key上
     */
    @Transactional
//    @CachePut(key = "#user.id")//(value = {"user"})
//    @CachePut(value = "user", key = "#user.id")
    @CacheEvict(value = "user",allEntries = true)
    public boolean updateById(User user) {
        int res = userMapper.updateById(user);
        if (res > 0) {
            //修改成功后
            log.info("清除缓存");
            return true;
        }
        return false;
    }

    @Transactional
    @CacheEvict(value = "user",allEntries = true)
    public int insert(User user) {
        //生成 token
        setToken(user);
        //保存信息到redis里
        log.info("userId={},token={}",user.getId(),user.getToken());
//        redisService.setString(CacheConstant.TOKEN_PREFIX + user.getId(), user.getToken(), 7200);
        //给密码加密
//        user.setPassword(EncryptUtil.getMd5(user.getPassword()));
        return userMapper.insert(user);
    }
    @Transactional
    @CacheEvict(value = "user",allEntries = true)
    public int delete(int id) {
        return userMapper.deleteById(id);
    }
    @Override
//    @Cacheable(cacheNames = "user")
    @Cacheable(cacheNames = {"user"})
    public List<User> list() {
        return super.list();
    }
    /**
     * 根据用户编号查询用户信息
     * @param id 用户编号
     * @return user用户实体类
     */
    @Cacheable(cacheNames = "user")
    public User getUserInfoById(int id) {
        User user = userMapper.selectById(id);
        if( null != user){
            user.setPassword(null);
        }
        return user;
    }

}
